// api/handlers/simple_handler.go
package handlers

import (
	"encoding/base64"
	"fmt"
	"mygin/pkg/response"
	"net/http"

	"github.com/gin-gonic/gin"
)

type SimpleHandler struct {
	// 可以在这里添加一些简单的依赖，如配置等
}

func NewSimpleHandler() *SimpleHandler {
	return &SimpleHandler{}
}

// 加密
func (h *SimpleHandler) Ping1(c *gin.Context) {
	decryptedData := c.Query("testname")

	if decryptedData == "" {
		c.JSON(http.StatusBadRequest, response.Fail(http.StatusBadRequest, "decryptedData cannot be empty"))
		return
	}

	// 32字节密钥 (AES-256)
	//key := []byte("0123456789abcdef0123456789abcdef")
	//plaintext := "Hello, cross-platform AES!"

	// 加密
	encrypted, iv, err := response.EncryptAES([]byte(decryptedData))
	if err != nil {
		panic(err)
	}
	fmt.Printf("Encrypted (Go): %s\n", base64.StdEncoding.EncodeToString(encrypted))
	fmt.Printf("IV (Go): %s\n", base64.StdEncoding.EncodeToString(iv))
	encryptedBase64 := base64.StdEncoding.EncodeToString(encrypted)
	ivBase64 := base64.StdEncoding.EncodeToString(iv)
	// 返回加密结果和IV
	c.JSON(http.StatusOK, response.Success("ok", gin.H{
		"encrypted": encryptedBase64,
		"iv":        ivBase64,
		"original":  decryptedData, // 如果需要也可以返回原始数据
	}))
}

func (h *SimpleHandler) Ping(c *gin.Context) {
	// 从上下文中获取预处理后的数据
	decryptedData, exists := c.Get("decryptedData")
	if !exists {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "data processing failed"})
		return
	}

	// 32字节密钥 (AES-256)
	//key := []byte("0123456789abcdef0123456789abcdef")
	plaintext := "Hello, cross-platform AES!"

	// 加密
	encrypted, iv, err := response.EncryptAES([]byte(plaintext))
	if err != nil {
		panic(err)
	}
	fmt.Printf("Encrypted (Go): %s\n", base64.StdEncoding.EncodeToString(encrypted))
	fmt.Printf("IV (Go): %s\n", base64.StdEncoding.EncodeToString(iv))

	//解密
	decrypted, err := response.DecryptAES(encrypted, iv)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Decrypted (Go): %s\n", string(decrypted))

	c.JSON(http.StatusOK, response.Success("ok", decryptedData))
}

func (h *SimpleHandler) GetInfo(c *gin.Context) {
	// 直接从请求中获取参数
	id := c.Param("id")

	c.JSON(http.StatusOK, gin.H{
		"id":   id,
		"info": "This is a simple response without service/repository layers",
	})
}
